<?php

namespace App\Http\Controllers\V1\Upload;

use App\Events\V1\ImportExportEvent;
use App\Http\Requests\V1\ImportDataRequest;
use App\Models\V1\Timetable;
use Illuminate\Http\Request;
use Jenssegers\Agent\Agent;
use Maatwebsite\Excel\Facades\Excel;
USE Log;
use Auth;


class TimetableExcelUploadController extends BaseExcelUploadController
{
    /**
     * 导入迎新日程数据
     *
     * @param Request $request
     */
    public function importData(ImportDataRequest $request)
    {
        $response = [
            'rspStatus' => false,
            'rspMsg' => '迎新日程数据导入失败！',
        ];

        if ($request->method() === 'POST') {
            // 验证请求
            $this->validateImport($request);
            $filePath = $request->input('successFile');
            $arrival_code = $this->getArrivalCode();
            if (empty($arrival_code)) {
                $response['rspStatus'] = false;
                $response['rspMsg'] = '请先启动迎新换届';
                return response()->json($response)->header('Content-Type', 'text/html;charset=utf-8');
            }
            Excel::load($filePath, function($reader) use ($arrival_code) {
                $reader->limitColumns(8);
                //忽略空的cells
                $reader->ignoreEmpty();
                $data = $reader->toArray();
                collect($data) -> flatMap(function($item) use ($arrival_code) {
                    $insert_data = [
                        'arrival_code' => $arrival_code,
                        'code' => $item[0],
                        'name' => $item[1],
                        'time' => $item[2],
                        'detail' => $item[3],
                        'address' => $item[4],
                        'reception_person' => $item[5],
                        'attention' => $item[6],
                        'show_order' => $item[7]
                    ];
                    if (!empty($item[0]) && !empty($item[1])) {
                        Timetable::updateOrCreate(['arrival_code'=>$arrival_code,'code'=>$item[0]],$insert_data);
                    }
                });
            });

            $response['rspStatus'] = true;
            $response['rspMsg'] = [
                'type' => 'import',
                'msg' => '成功导入['.$request->input('successFile').']文件',
            ];
            event(new ImportExportEvent(Auth::user(), new Agent(), $request->getClientIp(), time(), $response['rspMsg']));

            return response()->json($response)->header('Content-Type', 'text/html;charset=utf-8');
        }
    }

    /**
     * 导出迎新日程数据文件
     *
     * @param Request $request
     */
    public function exportData(Request $request)
    {
        $clientIP = $request->getClientIp();
        $header = ['迎新日程代码', '日程活动名称','日期', '具体时间要求', '地点','接待单位或人员','注意事项','显示顺序'];
        $arrival_code = $this->getArrivalCode();
        if (empty($arrival_code)) {
            $response['rspStatus'] = false;
            $response['rspMsg'] = '请先启动迎新换届';
            return response()->json($response)->header('Content-Type', 'text/html;charset=utf-8');
        }
        $custodian = Timetable::where('arrival_code',$arrival_code)->select('code', 'name','time','detail','address','reception_person','attention','show_order')->get();
        $cellDatas = [$header];
        foreach ($custodian as $item) {
            $cellData = [
                $item->code,
                $item->name,
                $item->time,
                $item->detail,
                $item->address,
                $item->reception_person,
                $item->attention,
                $item->show_order,
            ];
            array_push($cellDatas, $cellData);
        }

        Excel::create(iconv('UTF-8', 'GBK','迎新日程'), function ($excel) use ($cellDatas, $clientIP) {
            $excel->sheet('timetable', function ($sheet) use ($cellDatas) {
                $sheet->rows($cellDatas);
            });

            $response['rspMsg'] = [
                'type' => 'export',
                'msg' => '成功下载[迎新日程]导出文件',
            ];
            event(new ImportExportEvent(Auth::user(), new Agent(), $clientIP, time(), $response['rspMsg']));
        })->export('xls');
    }


    /****
     * 下载模版
     * @param Request $request
     */
    public function downData(Request $request)
    {
        $clientIP = $request->getClientIp();

        $header = [ '迎新日程代码', '日程活动名称','日期', '具体时间要求', '地点','接待单位或人员','注意事项','显示顺序'];
        $cellDatas = [$header];
        $cellData1 = ['TT10001','现场报到','8月28','请携带身份证于8月28日报到','东区教学楼132室','张老师','不要忘记携带必须品',1];
        array_push($cellDatas, $cellData1);
        Excel::create('迎新日程数据导入模版', function ($excel) use ($cellDatas, $clientIP) {
            $excel->sheet('timetable', function ($sheet) use ($cellDatas) {
                $sheet->rows($cellDatas);
            });
            $response['rspMsg'] = [
                'type' => 'export',
                'msg' => '成功下载[迎新日程]模版文件',
            ];
            event(new ImportExportEvent(Auth::user(), new Agent(), $clientIP, time(), $response['rspMsg']));
        })->export('xls');
    }
}
